<template>
  <div class="shopping-cart">
    <!-- 头部 -->
    <div class="header">
      <i class="fas fa-arrow-left" @click="goBack"></i>
      <h3>购物车</h3>
      <div class="header-placeholder"></div>
    </div>

    <!-- 购物车列表 -->
    <div class="cart-list">
      <div class="cart-item" v-for="item in cartItems" :key="item.id">
        <div class="item-left">
          <img :src="getFoodImage(item.foodDetails?.image)" alt="商品图片" class="food-img" @error="handleImageError">
        </div>

        <div class="item-center">
          <h4 class="food-name">{{ item.food?.foodName || '商品' }}</h4>
          <p class="food-desc" v-if="item.food?.foodExplain">{{ item.food?.foodExplain }}</p>
          <p class="food-price">¥{{ item. food?.foodPrice*item.quantity}}</p>
        </div>

        <div class="item-right">
          <div class="quantity-control">
            <button class="btn minus" @click="decreaseQuantity(item)">-</button>
            <span class="quantity">{{ item.quantity }}</span>
            <button class="btn plus" @click="increaseQuantity(item)">+</button>
          </div>
          <button class="delete-btn" @click="removeItem(item.food?.id)">
            <i class="fas fa-trash"></i>
          </button>
        </div>
      </div>
    </div>

    <!-- 空购物车 -->
    <div class="empty-cart" v-if="cartItems.length === 0 && !loading">
      <i class="fas fa-shopping-cart"></i>
      <p>购物车为空</p>
      <button class="go-shopping-btn" @click="goShopping">去购物</button>
    </div>

    <!-- 加载状态 -->
    <div class="loading" v-if="loading">
      <i class="fas fa-spinner fa-spin"></i>
      <p>加载中...</p>
    </div>

    <!-- 底部结算 -->
<!--    <div class="checkout-footer" v-if="cartItems.length > 0">-->
<!--      <div class="total-price">-->
<!--        总计: <span>¥{{ formatPrice(totalPrice) }}</span>-->
<!--      </div>-->
<!--      <button class="checkout-btn" @click="checkout">去结算</button>-->
<!--    </div>-->
  </div>
  <Footer></Footer>
</template>

<script setup>
import { ref, onMounted, computed } from 'vue'
import { useRouter } from 'vue-router'
import { cartAPI } from '@/api/cart.js'
import { foodAPI } from '@/api/food.js'
import Footer from "@/components/Footer.vue";

const router = useRouter()

// 响应式数据
const cartItems = ref([])
const loading = ref(false)

// 页面加载时获取购物车数据
onMounted(async () => {
  await loadCartItems()
})

// 加载购物车列表
const loadCartItems = async () => {
  loading.value = true
  try {
    const response = await cartAPI.getCartItems()

    // 根据你的API响应结构调整
    if (response.data && response.data.success === true && response.data.data) {
      cartItems.value = response.data.data
    } else if (response.data) {
      cartItems.value = response.data
    }
    // cartItems.value
    console.log( cartItems.value)
    // console.log( response.data.data )
    // 为每个商品获取详细信息
    await loadFoodDetails()

  } catch (error) {
    console.error('获取购物车列表失败:', error)
    alert('获取购物车列表失败')
  } finally {
    loading.value = false
  }
}

// 获取商品详情
const loadFoodDetails = async () => {
  for (let item of cartItems.value) {
    try {
      // console.log(item)
      const response = await foodAPI.getFoodById(item.food.id)
      if (response.data) {
        // 将商品详情添加到购物车项中
        console.log(response.data)
        item.foodDetails = response.data.data || response.data
      }
    } catch (error) {
      // console.log(item)
      console.error(`获取商品 ${item.food.id} 详情失败:`, error)
      item.foodDetails = { name: '商品信息加载失败' }
    }
  }
}

// 删除商品
const removeItem = async (itemId) => {
  if (!confirm('确定要删除这个商品吗？')) {
    return
  }

  try {
    const res=await cartAPI.removeCartItem(itemId)
    // console.log(res)
    // 从本地列表中移除
    cartItems.value = cartItems.value.filter(item => item.id !== itemId)
    loadCartItems();
    alert('删除成功')
  } catch (error) {
    console.error('删除商品失败:', error)
    loadCartItems();
    alert('删除商品失败')
  }
}

// 增加数量
const increaseQuantity = (item) => {
  item.quantity += 1
}

// 减少数量
const decreaseQuantity = (item) => {
  if (item.quantity > 1) {
    item.quantity -= 1
    // 这里可以加上更新购物车的API调用
  } else {
    // 如果数量为1，减少时询问是否删除
    if (confirm('数量为0将删除该商品，确定吗？')) {
      removeItem(item.id)
    }
  }
}

// 计算总价
const totalPrice = computed(() => {
  return cartItems.value.reduce((total, item) => {
    const price = item.foodDetails?.price || 0
    return total + (price * item.quantity)
  }, 0)
})

// 格式化价格
const formatPrice = (price) => {
  if (price === null || price === undefined) return '0.00'
  return parseFloat(price).toFixed(2)
}

// 获取商品图片
const getFoodImage = (imagePath) => {
  if (!imagePath) {
    return require('@/assets/logo.png') // 默认图片
  }
  return imagePath
}

// 图片加载错误处理
const handleImageError = (event) => {
  event.target.src = require('@/assets/logo.png')
}

// 返回上一页
const goBack = () => {
  router.back()
}

// 去购物
const goShopping = () => {
  router.push('/businessList')
}

// 去结算
const checkout = () => {
  if (cartItems.value.length === 0) {
    alert('购物车为空')
    return
  }
  // 这里可以跳转到订单确认页面
  router.push('/orders')
}
</script>

<style scoped>
.shopping-cart {
  min-height: 100vh;
  background-color: #f5f5f5;
  padding-bottom: 60px; /* 为底部结算栏留出空间 */
}

.header {
  display: flex;
  align-items: center;
  justify-content: space-between;
  padding: 4vw;
  background: white;
  border-bottom: 1px solid #eee;
}

.header i {
  font-size: 5vw;
  color: #666;
  cursor: pointer;
}

.header h3 {
  font-size: 4.5vw;
  font-weight: normal;
  color: #333;
}

.header-placeholder {
  width: 5vw;
}

.cart-list {
  padding: 4vw;
}

.cart-item {
  display: flex;
  background: white;
  padding: 4vw;
  border-radius: 2vw;
  margin-bottom: 4vw;
  align-items: center;
}

.item-left {
  margin-right: 4vw;
}

.food-img {
  width: 20vw;
  height: 20vw;
  border-radius: 2vw;
  object-fit: cover;
}

.item-center {
  flex: 1;
}

.food-name {
  margin: 0 0 2vw 0;
  font-size: 4vw;
  color: #333;
}

.food-desc {
  margin: 0 0 2vw 0;
  font-size: 3.5vw;
  color: #666;
}

.food-price {
  margin: 0;
  font-size: 4vw;
  color: #ff4757;
  font-weight: bold;
}

.item-right {
  display: flex;
  flex-direction: column;
  align-items: flex-end;
  gap: 3vw;
}

.quantity-control {
  display: flex;
  align-items: center;
  border: 1px solid #ddd;
  border-radius: 2vw;
  overflow: hidden;
}

.quantity-control .btn {
  width: 8vw;
  height: 8vw;
  border: none;
  background: #f5f5f5;
  font-size: 4vw;
  display: flex;
  align-items: center;
  justify-content: center;
}

.quantity {
  padding: 0 4vw;
  font-size: 4vw;
  min-width: 10vw;
  text-align: center;
}

.delete-btn {
  background: none;
  border: none;
  color: #ff4757;
  font-size: 4.5vw;
  cursor: pointer;
  padding: 2vw;
}

.empty-cart {
  text-align: center;
  padding: 20vw 4vw;
  color: #999;
}

.empty-cart i {
  font-size: 20vw;
  margin-bottom: 4vw;
}

.empty-cart p {
  font-size: 4vw;
  margin-bottom: 6vw;
}

.go-shopping-btn {
  background: linear-gradient(135deg, #ff6b6b, #ee5a24);
  color: white;
  border: none;
  padding: 3vw 8vw;
  border-radius: 2vw;
  font-size: 4vw;
  cursor: pointer;
}

.loading {
  text-align: center;
  padding: 20vw 4vw;
  color: #999;
}

.loading i {
  font-size: 8vw;
  margin-bottom: 4vw;
}

.checkout-footer {
  position: fixed;
  bottom: 0;
  left: 0;
  right: 0;
  background: white;
  padding: 3vw 4vw;
  display: flex;
  justify-content: space-between;
  align-items: center;
  border-top: 1px solid #eee;
  box-shadow: 0 -2px 10px rgba(0,0,0,0.1);
}

.total-price {
  font-size: 4.5vw;
  color: #333;
}

.total-price span {
  color: #ff4757;
  font-weight: bold;
}

.checkout-btn {
  background: linear-gradient(135deg, #ff6b6b, #ee5a24);
  color: white;
  border: none;
  padding: 3vw 6vw;
  border-radius: 2vw;
  font-size: 4vw;
  cursor: pointer;
}
</style>